<template>
  <div class="login">
    <el-form
      class="register-form"
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
    >
      <div class="title">登陆页</div>
      <el-form-item prop="phone">
        <el-input
          v-model="ruleForm.phone"
          type="text"
          placeholder="请输入手机号"
          size="large"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item prop="pass">
        <el-input
          v-model="ruleForm.pass"
          type="password"
          placeholder="请输入密码"
          size="large"
          autocomplete="off"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >登陆</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { user_login } from "../api/index";
import { filterRoutes } from "../utils/authorization";
import  routes  from "../router/routes";

let ruleForm = ref({ phone: "", pass: "" });
let ruleFormRef = ref();
let $router = useRouter();

const validatePhone = (rule, value, callback) => {
  if (/^1[3-9]\d{9}$/.test(value) == false) {
    callback(new Error("请输入正确的手机号"));
  } else {
    callback();
  }
};
const validatePass = (rule, value, callback) => {
  if (/^\d{4}$/.test(value) == false) {
    callback(new Error("请输入4位密码"));
  } else {
    callback();
  }
};
const rules = reactive({
  phone: [{ validator: validatePhone, trigger: "blur" }],
  pass: [{ validator: validatePass, trigger: "blur" }],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let res = await user_login(ruleForm.value);
      if (res.data.code == 200) {
        localStorage.setItem("token", res.data.token);
        localStorage.setItem("userinfo", JSON.stringify(res.data.userinfo));
        let accessRoutes = filterRoutes(
          routes,
          res.data.userinfo.role.permissions
        );
        accessRoutes.forEach((route) => {
          // 循环一次，添加一条路由
          $router.addRoute(route)
        });
        $router.push("/index");
      } else {
        ElNotification({
          title: "登陆通知",
          message: res.data.msg,
          type: "error",
        });
      }
    } else {
      return false;
    }
  });
};
</script>

<style scoped lang="scss">
.login {
  height: 100%;
  background: url("../assets/login.png") no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  .register-form {
    padding: 30px;
    min-width: 500px;
    border-radius: 5px;
    background-color: #fff;
  }
  .title {
    margin-bottom: 30px;
    font-size: 26px;
    font-weight: 700;
    text-align: center;
  }
}
</style>